// 新增部分代码（需要先导入相关模块）
import {_decorator, Component, director, Node, Vec2, Vec3} from 'cc';
import {GameEvent} from "db://assets/script/game-event";
import {FishAttackRecordReply} from "db://assets/proto/new-world-ws/v1/internal";
import {FreshImmortal} from "db://assets/proto/shared/v1/wuni";
import Long from "long";
import {FishBeAttackShockEvent} from "db://assets/script/common/events/fish-events/fish-be-attack-shock-event";

const {ccclass, property} = _decorator;

// 新增子弹组件
@ccclass('NormalAttackComp')
export class NormalAttackComp extends Component {
    @property
    speed: number = 50; // 子弹速度

    attackEvent: FishAttackRecordReply = null!

    _complete: boolean = false

    private targetNode: Node | null = null;

    init(attackEvent: FishAttackRecordReply, target: Node) {
        if (!target || !target.isValid) {
            this.node.destroy()
            return;
        }
        this.attackEvent = attackEvent;
        this.targetNode = target;
        // console.log('bullet start pos:', this.node.position, 'parent: ', this.node.parent)
        // console.log('attack target pos:', this.targetNode.getPosition())
        director.on(GameEvent.changeBattleRole, (fishId: Long) => {
            this.node.destroy()
            this._complete = true
        }, this)
    }

    protected onDestroy(): void {
        director.off(GameEvent.changeBattleRole, (fish: FreshImmortal) => {
            this.node.destroy()
        }, this)
    }

    // private tryDestroy() {
    //     this.node.destroy()
    // }

    update(dt: number) {
        if (this._complete) {
            return;
        }
        if (!this.targetNode || !this.targetNode.isValid) {
            this.node.destroy()
            return
        }

        // 1. 计算动态方向向量
        const targetPos = this.targetNode.worldPosition.clone();
        const bulletPos = this.node.worldPosition;
        let direction = targetPos.subtract(bulletPos).normalize();

        // 2. 添加随机扰动（曲线路径）
        // const randomFactor = 0.1; // 扰动强度
        // direction.x += (Math.random() - 0.5) * randomFactor;
        // direction.y += (Math.random() - 0.5) * randomFactor;
        // direction = direction.normalize();

        // 3. 计算子弹角度并平滑转向
        // 计算坐标差值
        // const dx = targetPos.x - bulletPos.x;
        // const dy = targetPos.y - bulletPos.y;

        // 计算角度（核心公式）
        const radians = Math.atan2(direction.y, direction.x); // 弧度值
        const degrees = radians * 180 / Math.PI;

        // 调整角度适配Cocos坐标系Ï
        // 应用旋转（三种方式任选）
        // 方式1：直接设置角度
        this.node.angle = degrees - 90;

        // 4. 更新位置（速度恒定）
        this.node.setWorldPosition(new Vec3(this.node.worldPosition.x + direction.x * this.speed * dt, this.node.worldPosition.y + direction.y * this.speed * dt, this.node.worldPosition.z))

        const distance = Vec2.distance(this.node.worldPosition, this.targetNode.worldPosition)
        // console.log(distance)
        // 5. 碰撞检测（可选）
        if (distance < 11) {
            this._complete = true
            this.node.destroy()
            director.emit(GameEvent.fishBeginBeAttack, this.attackEvent);
            director.emit(GameEvent.fishBeginBeAttackShock, new FishBeAttackShockEvent(this.attackEvent.defenceId, new Vec2(direction.x, direction.y), 5))
        }
    }
}